package com.albon.alarm;

import java.io.IOException;

import com.albon.soccer.DatabaseHelper;
import com.albon.soccer.Soccer;
import com.albon.util.Logg;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;

public class SoccerService extends Service implements VibrateType{
	private static final String TAG = "SoccerService";
	
	private MediaPlayer mMediaPlayer;
	private AudioManager mAudioManager;
	private Vibrator mVibrator;
	private String mTone;
	private ContentResolver mResolver;
	private int resetVolume;
	private int key = 1;
	private Soccer soccer;
	public void onCreate() {
		super.onCreate();
		
		Logg.e(TAG,"============onCreate============== ");	
		
		mMediaPlayer = new MediaPlayer();		
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		resetVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);// music 현재 볼륨을 가져와서 finish 할때 원복시켜준다.
		mVibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent == null) {
            stopSelf();
            return START_NOT_STICKY;
        }
		
		
		key = intent.getIntExtra("key", 1);
		call_alarm_values(key);
		
		Boolean mVibration = Boolean.valueOf(soccer.getAlarm_vibrate());
		String mRingtone = soccer.getAlarm_ringtone();
		if(mRingtone == null) {
			mRingtone = "";
		}
		wakeAlarm(mVibration, mRingtone);
		return START_STICKY;
	}
	 private int nMax;
	 public void wakeAlarm(boolean isVib, String ringtone) {
//			if(isUse_System_Sound()){//시스템 알람 소리 동일
			//if(false){//시스템 알람 소리 동일
			//	 mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
			//}else{
				 if(soccer.getAlarm_volume() == null || soccer.getAlarm_volume().equals("")){
					 nMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
					 mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, nMax, 0);
				 }else{
					 mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, Integer.parseInt(soccer.getAlarm_volume()), 0);	 
				 }
		//	}
			if(isVib) {
				Logg.e(TAG,"isVib : "+isVib);
				//mVibrator.vibrate(vibratePatterns, 0);
				playVibration();
			}
			
			try {		
		            
		            int status = 0;
		            String path = null;
		           
		           
		            	mMediaPlayer.setDataSource(this, Uri.parse(ringtone));
		            
		            if ( mMediaPlayer != null ) {
		            	mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				    	mMediaPlayer.setLooping(true);
				    	mMediaPlayer.setVolume(mAudioManager.getStreamVolume(AudioManager.STREAM_RING), mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
						mMediaPlayer.prepare();
		            }
				
			}
			catch (IllegalArgumentException e1) { 
				Logg.e(TAG, "e1 : "+e1);
			} 
			catch (SecurityException e2) {
				Logg.e(TAG, "e2 : "+e2);
			}
			catch (IllegalStateException e3) {
				Logg.e(TAG, "e3 : "+e3);
			}
			catch (IOException e4) {
				Logg.e(TAG, "e4 : "+e4);
				
			}
			
			if ( mMediaPlayer != null )
				mMediaPlayer.start();
		}
		
	private void playVibration() {

		int type = getVibrateType();

		long[] pattern = vib_patern[type];
		mVibrator.vibrate(pattern, 0);

	}

	private int getVibrateType() {
		int type = VIBRATE_DEFAULT;
		try {
			//바이브레이터 타입설정
		
		} catch (Exception e) {
			Logg.e(TAG, "e : " + e);
		}

		return type;

	}
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	//알람 값을 불러온다.
    void call_alarm_values(int _id){
    	SQLiteDatabase databse = null;		
		if(databse == null){
			databse = openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_ID + " = " +_id;		
		
		Cursor cursor = null;

		try {
			cursor = databse.rawQuery("SELECT "
					+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ENABLED + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAGUE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_STADIUM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_A_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_B_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SCORE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SMS + ", "
					+ DatabaseHelper.DATABASE_COLUMN_VIDEO + ", "
					+ DatabaseHelper.DATABASE_COLUMN_RECORD + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_HIGHLIGHT + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_POWER + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_EXPLANATION + " " + " FROM "
					+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
			if (cursor != null && cursor.moveToFirst()) {
				do {
					soccer = new Soccer(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23));
					
					
				} while (cursor.moveToNext());
			}		
					
								
		} finally {
			if (cursor != null)
				cursor.close();
			if(databse != null){
				databse.close();
			}
		}
    }
    
    @Override
	public void onDestroy() {
		
		releaseAlarm();
		mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);// music 볼륨을 기존 music 볼륨으로 초기화시킨다.
	}
	private void releaseAlarm() {
		if(mVibrator != null) {
			mVibrator.cancel();
		}
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
          
		}
	}
}
